import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import './FitnessHomepage.css';
import homepage from "./homepage.png"
import NewNavbar from './newHead';

// 默认用户信息
const DEFAULT_USER = {
  name: "健身爱好者",
  email: "",
  phone: "",
  gender: "保密",
  avatarUrl: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23757575'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z'/%3E%3Cpath d='M15 6.41L13.59 5l-3 3L8.41 7 10 5.41 15 10.41V6.41z'/%3E%3C/svg%3E",
  createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()
};

const FitnessHomepage = () => {
  const [searchParams] = useSearchParams();
  const emailFromUrl = searchParams.get('email');
  
  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    gender: ''
  });
  const [formError, setFormError] = useState('');
  // 新增：控制编辑状态（true=编辑模式，false=查看模式）
  const [isEditing, setIsEditing] = useState(false);

  // 初始化获取用户数据
  const fetchUserData = async () => {
    try {
      setLoading(true);
      setError(false);
      
      if (!emailFromUrl) {
        setError(true);
        setUserData(null);
        return;
      }
      
      const url = `http://localhost:5000/api/userinfo/select?email=${encodeURIComponent(emailFromUrl)}`;
      const response = await fetch(url);
      
      if (!response.ok) {
        if (response.status === 404) {
          setUserData({ ...DEFAULT_USER, email: emailFromUrl });
          return;
        }
        throw new Error('获取用户信息失败');
      }
      
      const data = await response.json();
      if (data && data.name && data.name !== DEFAULT_USER.name) {
        setUserData(data);
        // 初始化编辑表单数据（避免编辑时表单为空）
        setFormData({
          name: data.name || '',
          phone: data.phone || '',
          gender: data.gender || '保密'
        });
      } else {
        setUserData({ ...DEFAULT_USER, email: emailFromUrl });
      }
    } catch (err) {
      console.error('初始化获取用户数据出错:', err);
      setError(true);
      setUserData(emailFromUrl ? { ...DEFAULT_USER, email: emailFromUrl } : null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUserData();
  }, [emailFromUrl]);

  // 计算注册时长
  const [registrationDuration, setRegistrationDuration] = useState('');
  useEffect(() => {
    if (!userData?.createdAt) return;

    const calculateDuration = () => {
      const createdDate = new Date(userData.createdAt);
      const currentDate = new Date();
      const timeDiff = currentDate - createdDate;
      
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      const months = Math.floor(days / 30);
      const years = Math.floor(months / 12);

      if (years > 0) {
        setRegistrationDuration(`${years}年${months % 12}个月`);
      } else if (months > 0) {
        setRegistrationDuration(`${months}个月${days % 30}天`);
      } else {
        setRegistrationDuration(`${days}天`);
      }
    };

    calculateDuration();
    const intervalId = setInterval(calculateDuration, 86400000);
    return () => clearInterval(intervalId);
  }, [userData]);

  // 表单输入处理（新增/编辑通用）
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    if (formError) setFormError('');
  };

  // 新增：取消编辑（回到查看模式）
  const handleCancelEdit = () => {
    setIsEditing(false);
    setFormError('');
    // 重置表单为当前用户数据（避免编辑一半取消后表单残留）
    setFormData({
      name: userData.name || '',
      phone: userData.phone || '',
      gender: userData.gender || '保密'
    });
  };

  // 合并：新增/编辑通用的提交逻辑（根据userData判断是新增还是更新）
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 表单验证（复用原有逻辑）
    if (!formData.name.trim()) {
      setFormError('请输入您的姓名');
      return;
    }
    if (!formData.phone.trim() || !/^1[3-9]\d{9}$/.test(formData.phone)) {
      setFormError('请输入有效的11位手机号');
      return;
    }
    if (!formData.gender) {
      setFormError('请选择您的性别');
      return;
    }

    try {
      setLoading(true);
      setFormError('');
      
      // 区分：新增（用户未完善信息）vs 更新（用户编辑信息）
      const isUpdate = userData?.name !== DEFAULT_USER.name;
      const apiUrl = isUpdate 
        ? 'http://localhost:5000/api/userinfo/update' // 后端更新接口
        : 'http://localhost:5000/api/userinfo/add';  // 后端新增接口
      const method = 'POST'; // 若后端更新用PUT，可改为 isUpdate ? 'PUT' : 'POST'
      
      const response = await fetch(apiUrl, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
        },
        body: JSON.stringify({
          email: emailFromUrl, // 唯一标识，不变
          ...formData
        }),
      });
      
      if (response.ok) {
        // 构造新的用户数据
        const newUserData = {
          ...userData, // 保留原有不变的字段（如avatarUrl、createdAt）
          email: emailFromUrl,
          name: formData.name,
          phone: formData.phone,
          gender: formData.gender,
          // 若更新时需要记录修改时间，可新增updateAt字段
          updatedAt: new Date().toISOString()
        };
        
        setUserData(newUserData);
        setIsEditing(false); // 提交成功后回到查看模式（仅编辑时生效）
      } else {
        const errorData = await response.json();
        setFormError(errorData.message || (isUpdate ? '信息更新失败' : '信息保存失败') + '，请稍后再试');
      }
    } catch (err) {
      console.error('提交请求失败:', err);
      setFormError('网络错误，请检查您的连接');
    } finally {
      setLoading(false);
    }
  };

  // 加载状态
  if (loading) {
    return (
      <div className="fitness-homepage">
        <div className="fitness-loading-container">
          <div className="fitness-spinner"></div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  // 无email参数的错误提示
  if (error && !emailFromUrl) {
    return (
      <div className="fitness-homepage">
        <div className="error-container">
          <p>错误：未找到用户标识</p>
          <p>请通过登录页面重新进入</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <NewNavbar/>
      <div className="home-section">
        <div className="home-bg">
          <img 
            src={homepage}
            alt="健身背景" 
            className="home-img"
          />
          <div className="home-overlay"></div>
        </div>
        
        <div className='user-message'>
          {/* 场景1：用户已完善信息 → 显示查看/编辑模式 */}
          {userData && userData.name !== DEFAULT_USER.name ? (
            isEditing ? (
              // 编辑模式：显示表单（加载当前用户数据）
              <div className="registration-form" style={{ animation: 'fadeIn 0.5s ease' }}>
                <h2>编辑个人信息</h2>
                <p className="registration-description">
                  您的邮箱：<strong>{emailFromUrl}</strong>（邮箱不可修改）
                </p>
                
                <form onSubmit={handleSubmit} className="register-form">
                  <div className="form-group">
                    <label htmlFor="name">姓名</label>
                    <input
                      type="text"
                      id="name"
                      name="name"
                      value={formData.name}
                      onChange={handleInputChange}
                      placeholder="请输入真实姓名"
                      required
                      disabled={loading}
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="phone">手机号</label>
                    <input
                      type="tel"
                      id="phone"
                      name="phone"
                      value={formData.phone}
                      onChange={handleInputChange}
                      placeholder="请输入11位手机号"
                      required
                      disabled={loading}
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="gender">性别</label>
                    <select
                      id="gender"
                      name="gender"
                      value={formData.gender}
                      onChange={handleInputChange}
                      required
                      disabled={loading}
                    >
                      <option value="">请选择</option>
                      <option value="男">男</option>
                      <option value="女">女</option>
                      <option value="保密">保密</option>
                    </select>
                  </div>
                  
                  {formError && <p className="error-message">{formError}</p>}
                  
                  {/* 编辑模式：提交+取消按钮 */}
                  <div className="form-btn-group">
                    <button 
                      type="submit" 
                      className="register-btn"
                      disabled={loading}
                    >
                      {loading ? '更新中...' : '保存修改'}
                    </button>
                    <button 
                      type="button" 
                      className="cancel-btn"
                      onClick={handleCancelEdit}
                      disabled={loading}
                    >
                      取消
                    </button>
                  </div>
                </form>
              </div>
            ) : (
              // 查看模式：显示个人信息+编辑按钮
              <div className="user-profile" style={{ animation: 'fadeIn 0.5s ease' }}>
                <div className="profile-header-bar">
                  <h2>个人信息</h2>
                  {/* 编辑按钮：点击切换到编辑模式 */}
                  <button 
                    className="edit-profile-btn"
                    onClick={() => setIsEditing(true)}
                    disabled={loading}
                  >
                    编辑个人资料
                  </button>
                </div>
                
                {/* 头像+姓名区域 */}
                <div className="profile-header">
                  <img 
                    src={userData.avatarUrl} 
                    alt={`${userData.name}的头像`} 
                    className="profile-avatar"
                  />
                  <div className="profile-name-container">
                    <h3 className="profile-name">{userData.name}</h3>
                    <p className="profile-membership">
                      已完善信息 {registrationDuration}
                    </p>
                  </div>
                </div>
                
                {/* 详细信息区域（新增更新时间显示） */}
                <div className="profile-details">
                  <p><strong>邮箱:</strong> {userData.email}</p>
                  <p><strong>手机号:</strong> {userData.phone}</p>
                  <p><strong>性别:</strong> {userData.gender}</p>
                  <p><strong>完善信息时间:</strong> {new Date(userData.createdAt).toLocaleString()}</p>
                  {userData.updatedAt && (
                    <p><strong>最后修改时间:</strong> {new Date(userData.updatedAt).toLocaleString()}</p>
                  )}
                </div>
              </div>
            )
          ) : (
            // 场景2：用户未完善信息 → 显示初始完善表单（原有逻辑不变）
            <div className="registration-form" style={{ animation: 'fadeIn 0.5s ease' }}>
              <h2>完善您的个人信息</h2>
              <p className="registration-description">
                请补充以下信息，完成资料设置<br/>
                您的邮箱：<strong>{emailFromUrl}</strong>
              </p>
              
              <form onSubmit={handleSubmit} className="register-form">
                <div className="form-group">
                  <label htmlFor="name">姓名</label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    placeholder="请输入真实姓名"
                    required
                    disabled={loading}
                  />
                </div>
                
                <div className="form-group">
                  <label htmlFor="phone">手机号</label>
                  <input
                    type="tel"
                    id="phone"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    placeholder="请输入11位手机号"
                    required
                    disabled={loading}
                  />
                </div>
                
                <div className="form-group">
                  <label htmlFor="gender">性别</label>
                  <select
                    id="gender"
                    name="gender"
                    value={formData.gender}
                    onChange={handleInputChange}
                    required
                    disabled={loading}
                  >
                    <option value="">请选择</option>
                    <option value="男">男</option>
                    <option value="女">女</option>
                    <option value="保密">保密</option>
                  </select>
                </div>
                
                {formError && <p className="error-message">{formError}</p>}
                
                <button 
                  type="submit" 
                  className="register-btn"
                  disabled={loading}
                >
                  {loading ? '保存中...' : '完成并查看个人信息'}
                </button>
              </form>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default FitnessHomepage;